<?php

namespace App\Modules\Order\Controllers;

use App\Lib\Facades\FLAuth;
use App\Lib\Utilities;
use App\Modules\Member\Services\MemberService;
use App\Modules\MemberCard\Services\MemberCardService;
use App\Modules\Order\Services\HaircutPriceService;
use App\Modules\Order\Services\OrderCommentService;
use App\Modules\Order\Services\OrderService;
use App\Modules\Order\Transformers\GetScheduleAppTransformer;
use App\Modules\Order\Transformers\OrderListTransformer;
use App\Modules\Order\Validators\OrderControllerValidator;
use App\Modules\Pay\Services\PayService;
use Flower\Core\Http\BaseController;
use Flower\Core\Http\Request;
use Flower\Core\Http\Response;
use Flower\Core\Repository\Exceptions\ValidatorException;
use Flower\Facades\Flower;

class OrderController extends BaseController
{
	private $orderService;
	private $memberService;
	private $orderCommentService;
	private $memberCardService;
	private $payService;
	public function __construct(
		OrderService $orderService,
		MemberService $memberService,
		OrderCommentService $orderCommentService,
MemberCardService $memberCardService,PayService $payService)
	{
		$this->orderService = $orderService;
		$this->memberService = $memberService;
		$this->orderCommentService = $orderCommentService;
		$this->memberCardService = $memberCardService;
		$this->payService = $payService;
	}


	public function getRules()
	{
		return OrderControllerValidator::validator();
	}


	/**
	 * 获取服务价格
	 * @param Request $request
	 * @return mixed
	 * @throws \App\Exceptions\AllValidatorException
	 * @throws \App\Exceptions\NotFoundException
	 */
	public function getHairCutServiceTotalPrice(Request $request){
		$totalPrice = $this->orderService->hairCutTotalPrice($request->service_id,$request->count,$request->payment,$request->member_card_id);
		return $this->display($totalPrice);
	}

	/**
	 * 查询剪发师近期排班情况
	 * @param Request $request
	 * @return mixed
	 * @author Happy dong
	 * @modifiedTime 2019-08-09 09:39
	 */
	public function onDutyTime(Request $request)
	{
		$res = $this->orderService->scheduleOnDuty($request->store_id,$request->barber_id);
		return $this->display($res);
	}

	/**
	 * 查询某段时间内的理发师排班情况
	 * @param Request $request
	 * @return mixed
	 * @author Happy dong
	 * @modifiedTime 2019-08-09 09:39
	 */
	public function onDutyTimeApp(Request $request)
	{
		$list = $this->orderService->scheduleOnDutyApp($request->store_id,FLAuth::id());
		return $this->display((new GetScheduleAppTransformer($list))->transform());
	}


	/**
	 * 获取某天剪发师的时间预约情况
	 * @param Request $request
	 * @return mixed
	 * @author Happy dong
	 * @modifiedTime 2019-08-09 09:39
	 */
	public function dayAppointment(Request $request)
	{
		$res = $this->orderService->oneDaySchedule($request->store_id,$request->barber_id,$request->date);
		return $this->display($res);
	}

	/**
	 * 某天的预约状态 App
	 * @param Request $request
	 * @return mixed get_my_order_list_app
	 * @author Happy dong
	 * @modifiedTime 2019-08-09 09:39
	 */
	public function dayAppointmentApp(Request $request)
	{
		$date = date('Y-m-d',strtotime($request->date));
		$res = $this->orderService->oneDaySchedule($request->store_id,FLAuth::id(),$date, true);
		return $this->display($res);
	}


	/**
	 * 小程序预约下单
	 * @param Request $request
	 * @return mixed
	 * @throws \App\Exceptions\AllValidatorException
	 * @throws \App\Exceptions\NotFoundException
	 * @author Happy dong
	 * @modifiedTime 2019-08-02 17:25
	 */
	public function appointment(Request $request)
	{
		$memberId = FLAuth::id();
		// 预约订单
		$this->orderService->createAppointmentOrder($request->store_id,$request->barber_id,$memberId,$request->service_id,$request->appointment_time,$request->mobile,$request->payment,config('constant.appointment.online'),$request->nickname);
//		// 确认订单
//		$res = $this->orderService->confirmAppointment($appointmentOrder->barber_id,$appointmentOrder->id,true,$request->count,$request->portfolio_id);
//		if (!$res) return $this->error('预约订单失败！');
		return $this->success('预约订单成功!');
	}


	/**
	 * 小程序 取消预约订单
	 * @param Request $request
	 * @return mixed
	 * @throws \App\Exceptions\AllValidatorException
	 * @throws \App\Exceptions\NotFoundException
	 */
	public function cancelAppointmentWx(Request $request)
	{
		$res = $this->orderService->cancelAppointment(FLAuth::id(),$request->order_id,config('constant.appointmentCancelStatus.member'),$request->remark);
		if (!$res) return $this->error('取消预约失败！');
		return $this->success('取消预约成功!');

	}




	/**
	 * 取消订单申请微信
	 * @param Request $request
	 * @return mixed
	 * @throws \App\Exceptions\AllValidatorException
	 * @throws \App\Exceptions\NotFoundException
	 * @author Happy dong
	 * @modifiedTime 2019-08-06 20:08
	 */
	public function withdrawWx(Request $request){
	    $res = $this->orderService->cancelApply($request->order_id,config('constant.withdrawOrder.member'),$request->remark);
		if(empty($res)) return $this->error("取消订单申请正在处理中...");
		return $this->display($res,"取消订单申请成功");
	}

    /**
     * 拒绝取消
     * @param Request $request
     * @return mixed
     * @throws \App\Exceptions\NotFoundException
     */
	public function refusedCancelApply(Request $request){
        $res = $this->orderService->refusedCancel($request->order_cancel_id);
        if(empty($res)) return $this->error("拒绝取消订单，操作失败!");
        return $this->success("拒绝取消订单，操作成功！");
    }

    /**
     * 小程序拒绝消息已读
     * @param Request $request
     * @return mixed
     * @throws \App\Exceptions\NotFoundException
     */
    public function readCancelReasonWx(Request $request){
	    $res = $this->orderService->readCancelReason($request->order_cancel_id);
        if(empty($res)) return $this->error("消息读取，操作失败!");
        return $this->success("消息读取，操作成功！");
    }

    /**
     * APP拒绝消息 已读
     * @param Request $request
     * @return mixed
     * @throws \App\Exceptions\NotFoundException
     */
    public function readCancelReasonApp(Request $request){
        $res = $this->orderService->readCancelReason($request->order_cancel_id);
        if(empty($res)) return $this->error("消息读取，操作失败!");
        return $this->success("消息读取，操作成功！");
    }


	/**
	 * 同意取消
	 * @param Request $request
	 * @return mixed
	 * @throws \App\Exceptions\AllValidatorException
	 * @throws \App\Exceptions\NotFoundException
	 */
    public function agreeCancelApplyApp(Request $request){
        $res = $this->orderService->agreeApply($request->order_cancel_id,config('constant.message.scene.app'));
        if(empty($res)) return $this->error("同意取消订单，操作失败!");
        return $this->success("同意取消订单，操作成功！");
    }


	/**
	 * 取消订单微信
	 * @param Request $request
	 * @return mixed
	 * @throws \App\Exceptions\AllValidatorException
	 * @throws \App\Exceptions\NotFoundException
	 */
    public function  agreeCancelApplyWx(Request $request){
	    $res = $this->orderService->agreeApply($request->order_cancel_id,config('constant.message.scene.wx'));
	    if(empty($res)) return $this->error("同意取消订单，操作失败!");
	    return $this->success("同意取消订单，操作成功！");
    }

    /**
     * wx撤回取消申请
     * @param Request $request
     * @return mixed
     * @throws \App\Exceptions\NotFoundException
     */
    public function destroyCancelApplyWx(Request $request){
        $res = $this->orderService->destroyApply($request->order_cancel_id,config('constant.withdrawOrder.member'));
        if(empty($res)) return $this->error("撤回取消订单申请，操作失败!");
        return $this->success("撤回取消订单申请，操作成功！");
    }

    /**
     * App撤回取消申请
     * @param Request $request
     * @return mixed
     * @throws \App\Exceptions\NotFoundException
     */
    public function destroyCancelApplyApp(Request $request){
        $res = $this->orderService->destroyApply($request->order_cancel_id,config('constant.withdrawOrder.barber'));
        if(empty($res)) return $this->error("撤回取消订单申请，操作失败!");
        return $this->success("撤回取消订单申请，操作成功！");
    }


    /**
     * 取消订单申请app
     * @param Request $request
     * @return mixed
     * @throws \App\Exceptions\NotFoundException
     */
	public function withdrawApp(Request $request){
        $res = $this->orderService->cancelApply($request->order_id,config('constant.withdrawOrder.barber'),$request->remark);
		if(empty($res)) return $this->error("取消订单申请失败");
		return $this->success("取消订单申请成功！");
	}



	/**
	 * App 取消预约订单
	 * @param Request $request
	 * @return mixed
	 * @throws \App\Exceptions\AllValidatorException
	 * @throws \App\Exceptions\NotFoundException
	 * @author Happy dong
	 * @modifiedTime 2019-08-09 09:39
	 */
	public function cancelAppointmentApp(Request $request)
	{
		$res = $this->orderService->cancelAppointment(FLAuth::id(),$request->order_id,config('constant.appointmentCancelStatus.barber'),$request->remark);
		if (!$res) return $this->error('取消预约失败！');
		return $this->success('取消预约成功!');
	}

	/**
	 * 取消订单
	 * @param Request $request
	 * @return mixed
	 * @throws \App\Exceptions\AllValidatorException
	 * @throws \App\Exceptions\NotFoundException
	 */
	public function cancelOrderApp(Request $request){
		$res = $this->orderService->cancelOrder(FLAuth::id(),$request->order_id,config('constant.appointmentCancelStatus.barber'),$request->remark);
		if (!$res) return $this->error('取消订单失败！');
		return $this->success('取消订单成功!');
	}






	/**
	 * 后台逻辑自动取消超时预约订单
	 * @param $parmas
	 * @return mixed
	 * @throws \App\Exceptions\AllValidatorException
	 * @throws \App\Exceptions\NotFoundException
	 * @author Happy dong
	 * @modifiedTime 2019-08-09 09:40
	 */
	public function cancelAppointmentAdmin($params)
	{
		$res = $this->orderService->cancelAppointment(0,$params['order_id'],config('constant.appointmentCancelStatus.system'),$params['remark']);
		if (!$res) return $this->error('取消预约失败！');
		return $this->success('取消预约成功!');
	}


	/**
	 * 定时任务 取消过期订单列表
	 * @return mixed
	 */
	public function expiredOrderList(){
		$res = $this->orderService->setExpiredOrderList();
		return $this->success('逾期订单，设置完成');
	}


	/**
	 * 理发师确人预约订单接单
	 * @param Request $request
	 * @return mixed
	 * @throws \App\Exceptions\NotFoundException
	 * @author Happy dong
	 * @modifiedTime 2019-08-02 17:23
	 * @todo 暂时取消不用
	 */
//	public function confirmAppointmentOrder(Request $request)
//	{
//		$res = $this->orderService->confirmAppointment(FLAuth::id(),$request->appointment_id);
//		if (!$res) return $this->error('订单确认失败！');
//		return $this->success('订单确认成功!');
//	}

	/**
	 * 小程序获取预约列表
	 * @param Request $request
	 * @return mixed
	 * @throws \Flower\Core\Repository\Exceptions\RepositoryException
	 */
	public function getAppointmentList(Request $request)
	{
		$params = $request->all();
		$params['member_id'] = FLAuth::id();
		$res = $this->orderService->getAppointmentList($params);
		if (!$res) return $this->error('获取预约订单失败！');
		return $this->display($res);
	}


	/**
	 * 理发师服务完成 提交付款完成后的订单
	 * @param Request $request
	 * @return mixed
	 * @throws \App\Exceptions\AllValidatorException
	 * @throws \App\Exceptions\DbException
	 * @throws \App\Exceptions\NotFoundException
	 */
	public function orderFinished(Request $request)
	{
		$storeId = $request->input('store_id');
		$payment = $request->input('payment');
		$changeReason = $request->input('change_reason');
		$finishRemark = $request->input('finish_remark');
		$bill_info = $request->input('bill_info');
		$coupon_code = $request->input('coupon_code');
		$result = $this->orderService->finishedOrder($request->bill_id,$request->member_card_id,$bill_info,$storeId);
		if(!$result['status']){
			return $this->handleApiResult($result);
		}
		$orderItems = $result['data']['orderItems'];
		$memberCard = $result['data']['memberCard'];
		//		$assistantId = $result['assistantId'];
		$order = $this->payService->Pay($result['data']['order'],1,$request->bill_id,compact('orderItems','payment','memberCard','changeReason','finishRemark','coupon_code'));
		return $this->success('付款成功!');
	}


	/**
	 * 小程序端订单查询
	 * @param Request $request
	 * @return mixed
	 * @throws \Flower\Core\Repository\Exceptions\RepositoryException
	 * @author Happy dong
	 * @modifiedTime 2019-08-09 09:40
	 */
	public function searchOrderListWx(Request $request)
	{
		$list = $this->orderService->searchOrderList(FLAuth::id(),$request->status,$request->page_size,$request->order_no);
		$list = (new OrderListTransformer($list,false))->transform();
		$list = Utilities::dealPage($list);
		return $this->display($list);
	}


	/**
	 * app端订单查询理发师
	 * @param Request $request
	 * @return mixed
	 * @throws \App\Exceptions\NotFoundException
	 * @throws \Flower\Core\Repository\Exceptions\RepositoryException
	 * @author Happy dong
	 * @modifiedTime 2019-08-09 09:40
	 */
	public function getMyOrderList(Request $request)
	{
		if(!$request->has('store_id') || !$request->has('status')){
			return $this->error("店铺Id或订单状态参数缺失错误");
		}
		$pageSize = $request->input('page_size',10);
		$list = $this->orderService->searchOrderBarber(FLAuth::id(),$request->store_id,$request->status,$pageSize,$request->keyword);
		$list = (new OrderListTransformer($list))->transform();
		$list = Utilities::dealPage($list);
		return $this->display($list);
	}


	/**
	 * app端订单查询 店长
	 * @param Request $request
	 * @return mixed
	 * @throws \App\Exceptions\NotFoundException
	 * @throws \Flower\Core\Repository\Exceptions\RepositoryException
	 * @author Happy dong
	 * @modifiedTime 2019-08-09 09:43
	 */
	public function getOrderList(Request $request)
	{
		if(!$request->has('store_id') || !$request->has('status')){
			return $this->error("店铺Id或订单状态参数缺失错误");
		}
		$pageSize = $request->input('page_size',10);
		$list = $this->orderService->searchOrderBarber(0,$request->store_id,$request->status,$pageSize,$request->keyword);
		$list = (new OrderListTransformer($list))->transform();
		$list = Utilities::dealPage($list);
		return $this->display($list);
	}


	/**
	 *  用户评价订单
	 * @param Request $request
	 * @return mixed
	 * @throws \App\Exceptions\NotFoundException
	 */
	public function orderComment(Request $request)
	{
		$res = $this->orderCommentService->orderComment(FLAuth::id(),$request->order_id,$request->comment,$request->image,$request->video,$request->score_attitude,$request->score_skill,$request->score_appearance,$request->score_store,$request->waiting_time);
		if (!$res) return $this->error('订单评价失败！');
		return $this->success("订单评价成功！");
	}


	/**
	 * 获取订单评价  小程序端订单评级
	 * @param Request $request
	 * @return mixed
	 */
	public function getOrderComment(Request $request)
	{
		$res = $this->orderCommentService->getOrderComment($request->all());
		if (!$res) return $this->error('获取订单评价失败！');
		return $this->display($res, "获取订单评价成功！");
	}


	/**
	 * 删除订单评论wx
	 * @param Request $request
	 * @return mixed
	 * @throws ValidatorException
	 * @throws \App\Exceptions\NotFoundException
	 * @author Happy dong
	 * @modifiedTime 2019-08-10 16:07
	 * @todo 预留订单评价删除
	 */
	public function deleteOrderComment(Request $request)
	{
		$res = $this->orderCommentService->deleteComment(FLAuth::id(),$request->order_comment_id);
		if (!$res) return $this->error('删除订单评价失败！');
		return $this->display($res, "删除订单评价成功！");
	}

	/**
	 * 理发师回复订单评价
	 * @param Request $request
	 * @return mixed
	 * @throws \App\Exceptions\NotFoundException
	 */
	public function addCommentReply(Request $request)
	{
		if(!$request->has('comment_id') || !$request->has('contents')){
			return $this->error("评论id或者回复评论内容参数缺失");
		}
		$res = $this->orderCommentService->orderReply(FLAuth::id(),$request->comment_id,$request->contents);
		if (!$res) return $this->error('订单评价回复失败！');
		return $this->success("订单评价回复成功！");
	}


	public function delOrderCommentReply(Request $request)
	{
		$res = $this->orderCommentService->deleteReply($request->all());
		if (!$res) return $this->error('订单评价回复删除失败！');
		return $this->success("订单评价回复删除成功！");
	}

	/**
	 * 评论点赞
	 * @param Request $request
	 * @return mixed
	 * @throws \App\Exceptions\NotFoundException
	 * @author Happy dong
	 * @modifiedTime 2019-07-31 17:36
	 */
	public function addOrderCommentLike(Request $request)
	{
		$res = $this->orderCommentService->addCommentLike($request->member_id, $request->comment_id);
		if (!$res) return $this->error('订单评价点赞失败！');
		return $this->success("订单评价点赞成功！");
	}

	/**
	 *
	 * @param Request $request
	 * @return mixed
	 */
	public function delOrderCommentLike(Request $request)
	{
		$res = $this->orderCommentService->delCommentLike($request->comment_id,FLAuth::id());
		if (!$res) return $this->error('订单评价点赞删除失败！');
		return $this->success("订单评价点赞删除成功！");
	}

	/**
	 * 今日营业额数据统计 店长端
	 * @param Request $request
	 * @return mixed
	 */
	public function orderToday(Request $request)
	{
		$res = $this->orderService->orderToday($request->all());
		if (!$res) return $this->error('获取数据失败！');
		return $this->display($res);
	}

	/**
	 * 获取理发师当天提成
	 * @param Request $request
	 * @return mixed
	 */
//	public function getUserTodayRoyalty(Request $request){
//		try{
//			$res = $this->orderService->getUserTodayRoyalty($request->all());
//			return $this->display($res);
//		}catch (ValidatorException $e){
//			$msg = array_values($e->getMessageBag()->getMessages())[0][0];
//			return $this->error($msg);
//		}
//	}

	/**
	 * 店铺今七天的营业额
	 * @param Request $request
	 * @return mixed
	 */
	public function weekTurnOver(Request $request)
	{
		$res = $this->orderService->weekTurnOver($request->all());
		return $this->display($res);
	}


	/**
	 * 评论查看次数自增1
	 * @param Request $request
	 * @return mixed
	 */
	public function orderCommentViewTimesSetInc(Request $request){
		$res = $this->orderCommentService->commentViewTimesSetInc($request->comment_id);
		if(empty($res)) return $this->error("评论查看次数加1，失败");
		return $this->success("评论查看次数加1，成功");
	}

	/**
	 * app端的预约列表
	 * @param Request $request
	 * @return mixed
	 */
	public function getAppointmentApp(Request $request)
    {
        $store_id = $request->input('store_id');
        $is_barber = $request->input('is_barber');
        $user_id = FLAuth::id();
        $status = $request->input('status');
        $source = $request->input('source');
        $keywords = $request->input('keywords');
        $pageSize = $request->input('pageSize',10);
        $data = $this->orderService->getAppointmentApp($store_id,$is_barber,$user_id,$status,$source,$keywords,$pageSize);
        return $this->display($data);
    }

	/**
	 *  Pad端的预约列表
	 * @param Request $request
	 * @return mixed
	 * @throws \Flower\Core\Repository\Exceptions\RepositoryException
	 */
//    public function getAppointmentPad(Request $request){
//	    $store_id = $request->input('store_id');
//	    $is_barber = $request->input('is_barber');
//	    $user_id = FLAuth::id();
//	    $status = $request->input('status');
//	    $source = $request->input('source');
//	    $keywords = $request->input('keywords');
//	    $pageSize = $request->input('pageSize',10);
//	    $data = $this->orderService->getAppointmentPad($store_id,$is_barber,$user_id,$status,$source,$keywords,$pageSize);
//	    return $this->display($data);
//    }


	/**
	 * 获取理发师的预约开单列表
	 * @param Request $request
	 * @return mixed
	 */
    public function getAppointBillOrderList(Request $request){
    	$store_id = $request->input('store_id');
    	$barber_id = $request->input('barber_id');
    	$pageSize = $request->input('page_size');
    	$pageSize = empty($pageSize) ? 10 : $pageSize;
    	$barber_id = empty($barber_id) ? FLAuth::id() : $barber_id;
    	$list = $this->orderService->getAppointmentBillOrderList($store_id,$barber_id,$pageSize);
    	$list = Utilities::dealPage($list);
    	return $this->display($list);
    }

}
